package cn.jinjimi.app.managers.task;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by lforxeverc on 2016/10/31.
 */

public class TaskPoolManager {
    private static volatile TaskPoolManager instance = null;
    private static Map<String, BaseTaskPool> mPoolMap = new HashMap<>();

    static {
        mPoolMap.put(TaskPoolName.DEFAULT, new BaseTaskPool() {
            @Override
            public String name() {
                return TaskPoolName.DEFAULT;
            }
        });
        mPoolMap.put(TaskPoolName.GUIDE_POOL_NAME, new BaseTaskPool() {
            @Override
            public String name() {
                return TaskPoolName.GUIDE_POOL_NAME;
            }
        });

    }

    public static TaskPoolManager getInstance() {
        if (instance == null) {
            synchronized (TaskPoolManager.class) {
                if (instance == null) {
                    instance = new TaskPoolManager();
                }
            }
        }
        return instance;
    }

    public synchronized <T extends BaseTask> void push(T task) {
        if (task != null) {
            final String poolName = task.poolName();
            if (!mPoolMap.containsKey(poolName)) {
                mPoolMap.put(poolName, new BaseTaskPool() {
                    @Override
                    public String name() {
                        return poolName;
                    }
                });
            }
            if (mPoolMap.containsKey(poolName)) {
                mPoolMap.get(poolName).push(task);
                mPoolMap.get(poolName).notifyAll(task, true);
            }
        }
    }

    public synchronized void pop() {
        pop(TaskPoolName.DEFAULT);
    }

    public synchronized <T extends BaseTask> void pop(String poolName) {
        if (mPoolMap.containsKey(poolName)) {
            BaseTask bt = mPoolMap.get(poolName).pop();
            if (bt != null)
                mPoolMap.get(poolName).notifyAll(bt, false);
        }

    }

    public synchronized void cancelAllWithPoolName(String poolName) {
        if (mPoolMap.containsKey(poolName)) {
            mPoolMap.get(poolName).cancelAll();
        }
    }

    public synchronized void cancelAll() {
        for (String poolName : mPoolMap.keySet()) {
            cancelAllWithPoolName(poolName);
        }
    }

    public synchronized void addTaskPoolListenerWithName(String poolName, IPoolChangeObserver l) {
        if (mPoolMap.containsKey(poolName)) {
            mPoolMap.get(poolName).addObserver(l);
        }
    }

    public synchronized void removeTaskPoolListenerWithName(String poolName, IPoolChangeObserver l) {
        if (mPoolMap.containsKey(poolName)) {
            mPoolMap.get(poolName).removeObserver(l);
        }
    }

    public synchronized void removeAllTaskPoolListenerWithName(String poolName) {
        if (mPoolMap.containsKey(poolName)) {
            mPoolMap.get(poolName).removeObserver(null);
        }
    }

}

